﻿using MongoDB.Driver;
using System.Linq.Expressions;
using Testudo.Core;

namespace Testudo.Mongo;

public static class MongoCollectionExtensions
{
    public static async Task<PagingList<TEntity>> PagingListAsync<TEntity>(this IMongoCollection<TEntity> target,
        Expression<Func<TEntity, bool>> filter = null, int pageIndex = 1, int pageSize = 10)
    {
        var totalCount = await target.CountDocumentsAsync(filter);
        pageSize = Math.Max(10, Math.Min(100, pageSize));
        pageIndex = Math.Min((int)Math.Ceiling(totalCount * 1.0 / pageSize), Math.Max(1, pageIndex));
        return new PagingList<TEntity>
        {
            PageIndex = pageIndex,
            PageSize = pageSize,
            TotalCount = (int)totalCount,
            Data = target.Find(filter).Skip((pageIndex - 1) * pageSize).Limit(pageSize).ToList()
        };
    }
}